#!/bin/bash

set -e

ROOT=${ROOT:-$(pwd)}
TYPE=$1
SERVICE=$2

service_dir=$ROOT/$SERVICE

display_usage () {
    echo "Usage: $0 TYPE SERVICE"
}

# Check if there are at least 2 arguments
if [ $# -lt 2 ]; then
    display_usage
    exit 1
fi

# Check if the service exists
if [ ! -f $service_dir/metadata.yaml ]; then
    echo "Service $SERVICE does not exist"
    exit 1
fi

# Check for quiet mode
if [ ! -z $QUIET ]; then
    export OUTPUT_FILE=$(mktemp)
    exec 5>&1 6>&2 1>$OUTPUT_FILE 2>&1
fi

cleanup () {
    CODE=$?
    if [ ! -z $QUIET ]; then
        if [ ! $CODE -eq 0 ]; then
            cat $OUTPUT_FILE >&5
        fi
        rm $OUTPUT_FILE
    fi
}
trap cleanup EXIT

check-deps_cloudformation () {
    # Gather dependencies
    dependencies=$(yq -r ' .dependencies[]? ' $service_dir/metadata.yaml)
    # If it contains '*', this means all other services must be deployed
    echo "$dependencies" | grep -q \* && {
        dependencies="$($ROOT/tools/services --exclude ${SERVICE})"
    }
    echo dependencies=$dependencies

    # Check if all dependencies are deployed
    for dependency in $dependencies; do
        stack_name=${DOMAIN:-ecommerce}-${ENVIRONMENT:-dev}-${dependency}
        aws cloudformation describe-stacks --stack-name $stack_name | \
            jq -r ' .Stacks |
                map(
                    .StackStatus
                    | test("(CREATE_FAILED|ROLLBACK_IN_PROGRESS|ROLLBACK_COMPLETE|ROLLBACK_FAILED|DELETE_IN_PROGRESS|DELETE_COMPLETE|DELETE_FAILED)")
                    | not
                ) ' | \
            grep -q "true" && {
                FOUND=true
            }

        # Checking in case the service doesn't support environments
        if [ -z $FOUND ]; then
            echo "Stack $stack_name not found"
             stack_name=${DOMAIN:-ecommerce}-${dependency}
            aws cloudformation describe-stacks --stack-name $stack_name | \
                jq -r ' .Stacks |
                    map(
                        .StackStatus
                        | test("(CREATE_FAILED|ROLLBACK_IN_PROGRESS|ROLLBACK_COMPLETE|ROLLBACK_FAILED|DELETE_IN_PROGRESS|DELETE_COMPLETE|DELETE_FAILED)")
                        | not
                    ) ' | \
                grep -q "true" && {
                    FOUND=true
                }
        fi

        if [ -z $FOUND ]; then
            echo "Stack $stack_name not found"
            exit 1
        fi
    done
}

type check-deps_$TYPE | grep -q "function" &>/dev/null || {
    echo "Unsupported type: $TYPE"
    echo
    display_usage
    exit 1
}
check-deps_$TYPE